package com.zzh.config;

import com.alibaba.fastjson.JSON;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.MessageConversionException;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author 张占恒.
 * @date 2020/8/28.
 * @time 14:23.
 */
@Configuration
public class RabbitmqConfig {
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMandatory(true);
        rabbitTemplate.setConfirmCallback(new MyConfirmCallback());
        rabbitTemplate.setMandatory(true);
        //失败回调
        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            @Override
            public void returnedMessage(Message message, int i, String s, String s1, String s2) {
                //发送消息对象
                System.out.println(message);
                //状态码
                System.out.println(i);
                //失败信息
                System.out.println(s);
                //交换机
                System.out.println(s1);
                //路由键
                System.out.println(s2);
            }
        });
        //自定义字符转换
        rabbitTemplate.setMessageConverter(new MessageConverter() {
            //发送消息
            @Override
            public Message toMessage(Object o, MessageProperties messageProperties) throws MessageConversionException {
                messageProperties.setContentType("text/xml");
                Message message = new Message(JSON.toJSONBytes(o),messageProperties);

                return message;
            }

            @Override
            public Object fromMessage(Message message) throws MessageConversionException {
                return null;
            }
        });
        return rabbitTemplate;
    }
    private class MyConfirmCallback implements RabbitTemplate.ConfirmCallback {
        @Override
        public void confirm(CorrelationData correlationData, boolean b, String s) {
            System.out.println(b);//需要的时间
            System.out.println(s);//失败的原因
            System.out.println(correlationData);//id
        }
    }
}
